/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.dpy.appmvdpy.Facades;

import com.dpy.appmvdpy.Models.Clientes;
import com.dpy.appmvdpy.Models.Users;
import java.util.List;
import javax.persistence.Query;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author ac_psoares
 */
@Component
@Scope(value="request")
public class ClientesFacade extends DefaultFacade<Clientes> {

     public ClientesFacade()
    {
       super(Clientes.class);
    }
    
    @Override
    public void setId(Clientes entity) {
          entity.setId(this.getMaxId()+1);
    }
    
    @Transactional(readOnly=true)
    public Clientes getClienteByCnpj(String cnpj)
    {
        Query q = em.createQuery("SELECT c from Clientes as c where c.cnpj = :cnpj ");
        q.setParameter("cnpj", cnpj);
        return q.getResultList().size() == 1 ? (Clientes)q.getResultList().get(0) : null;    
    }
    
    @Transactional(readOnly=true)
    public List<Clientes> listAll(int pag)
    {
       Query q = em.createQuery("SELECT c from Clientes as c ORDER BY c.integrado ASC, c.nome ASC");
       q.setFirstResult(pag * 100);
       q.setMaxResults(100);
       return q.getResultList();
    }
    
    @Transactional(readOnly=true)
    public List<Clientes> listAll()
    {
       Query q = em.createQuery("SELECT c from Clientes as c ORDER BY c.integrado ASC, c.nome ASC");
       return q.getResultList();
    }

    public List<Clientes> listByVendedorId(Integer id, int pag) {
        Query q = em.createQuery("SELECT c from Clientes as c where c.vendedor.id = :id ORDER BY c.integrado ASC, c.nome ASC");
        q.setParameter("id", id);
        q.setFirstResult(pag * 100);
        q.setMaxResults(100);
        return q.getResultList();
    }
    
    @Transactional
    public int pageNumbers(int id)
    {   
        Query q = em.createQuery("SELECT c from Clientes as c where c.vendedor.id = :id ");
        q.setParameter("id", id);
        return (q.getResultList().size() / 100); 
    }

   @Transactional 
    public Object listByVendedorId(Integer id) {
        Query q = em.createQuery("SELECT c from Clientes as c where c.vendedor.id = :id ORDER BY c.nome");
        q.setParameter("id", id);
        return q.getResultList(); 
    }
   
     @Transactional
      public Clientes getByCodigoDpy(String codigoDPY) {
        Query q = em.createQuery("SELECT c from Clientes as c where c.codigo = :codigo");
        q.setParameter("codigo", codigoDPY);
       
        if (q.getResultList().isEmpty())
            return new Clientes();
        else
            return (Clientes) q.getSingleResult();
      }
}
